package online.chazi.netkit.messaging;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * 说明：作者很懒，什么都没留下
 * Created by 叉子同学 on 2020-04-24 15:31
 */
public class MessageProtocolDecoder extends ByteToMessageDecoder {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() < Message.HEADER_SIZE) {
            return;
        }
        byteBuf.markReaderIndex();
        try {
            int id = byteBuf.readInt();
            byte extension = byteBuf.readByte();
            int contentLength = byteBuf.readInt();
            if (byteBuf.readableBytes() < contentLength) {
                byteBuf.resetReaderIndex();
            } else {
                byte[] data = new byte[contentLength];
                byteBuf.readBytes(data);
                list.add(new Message(id, extension, data));
            }
        } catch (Exception e) {
            byteBuf.resetReaderIndex();
        }
    }

}